'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { User, Settings, LogOut, Shield, TestTube } from 'lucide-react'
import { useCurrentUser } from '@/hooks/use-auth'
import { useToast } from '@/hooks/use-toast'

export function UserAvatar() {
  const { user, loading } = useCurrentUser()
  const [loggingOut, setLoggingOut] = useState(false)
  const router = useRouter()
  const { toast } = useToast()

  const handleLogout = async () => {
    setLoggingOut(true)
    try {
      await fetch('/api/auth/logout', { method: 'POST' })
      toast({
        title: "登出成功",
        description: "您已安全登出系统",
      })
      router.push('/login')
    } catch (error) {
      console.error('登出失败:', error)
      toast({
        title: "登出失败",
        description: "请稍后重试",
        variant: "destructive",
      })
    } finally {
      setLoggingOut(false)
    }
  }

  const getRoleColor = (roleCode: string) => {
    const colors: Record<string, string> = {
      'ADMIN': 'bg-red-100 text-red-800',
      'A': 'bg-red-100 text-red-800',
      'PROCUREMENT': 'bg-blue-100 text-blue-800',
      'P': 'bg-blue-100 text-blue-800',
      'DESIGN': 'bg-green-100 text-green-800',
      'E': 'bg-green-100 text-green-800',
      'MONITORING': 'bg-orange-100 text-orange-800',
      'M': 'bg-orange-100 text-orange-800',
      'CONSTRUCTION': 'bg-yellow-100 text-yellow-800',
      'C': 'bg-yellow-100 text-yellow-800',
      'CONSTRUCTION_BUILD': 'bg-indigo-100 text-indigo-800',
      'O': 'bg-indigo-100 text-indigo-800',
      'OPERATIONS': 'bg-purple-100 text-purple-800',
      'R': 'bg-purple-100 text-purple-800',
      'VIEWER': 'bg-gray-100 text-gray-800',
      'V': 'bg-gray-100 text-gray-800'
    }
    return colors[roleCode] || 'bg-gray-100 text-gray-800'
  }

  const getInitials = (name: string) => {
    return name
      .split(' ')
      .map(word => word.charAt(0))
      .join('')
      .toUpperCase()
      .slice(0, 2)
  }

  if (loading) {
    return (
      <div className="flex items-center space-x-2">
        <div className="animate-pulse">
          <div className="w-8 h-8 bg-gray-200 rounded-full"></div>
        </div>
      </div>
    )
  }

  if (!user) {
    return (
      <Button variant="outline" onClick={() => router.push('/login')}>
        登录
      </Button>
    )
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="ghost" className="relative h-10 w-auto px-2">
          <div className="flex items-center space-x-3">
            <Avatar className="h-8 w-8">
              <AvatarFallback className="bg-blue-500 text-white text-sm font-medium">
                {getInitials(user.full_name)}
              </AvatarFallback>
            </Avatar>
            <div className="hidden md:block text-left">
              <div className="text-sm font-medium text-gray-900">{user.full_name}</div>
              <div className="text-xs text-gray-500">@{user.username}</div>
            </div>
            {/* Badge 已隐藏 */}
            {/* <Badge className={`hidden sm:inline-flex text-xs ${getRoleColor(user.role_code)}`}>
              {user.role_name}
            </Badge> */}
          </div>
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent className="w-64" align="end" forceMount>
        <DropdownMenuLabel className="font-normal">
          <div className="flex flex-col space-y-2">
            <div className="flex items-center space-x-2">
              <Avatar className="h-10 w-10">
                <AvatarFallback className="bg-blue-500 text-white">
                  {getInitials(user.full_name)}
                </AvatarFallback>
              </Avatar>
              <div className="flex-1">
                <p className="text-sm font-medium leading-none">{user.full_name}</p>
                <p className="text-xs leading-none text-muted-foreground mt-1">
                  @{user.username}
                </p>
              </div>
            </div>
            {/* Badge 已隐藏 */}
            {/* <Badge className={`w-fit text-xs ${getRoleColor(user.role_code)}`}>
              {user.role_name}
            </Badge> */}
          </div>
        </DropdownMenuLabel>
        <DropdownMenuSeparator />
        
        <DropdownMenuItem onClick={() => router.push('/test-permissions')}>
          <TestTube className="mr-2 h-4 w-4" />
          <span>权限测试</span>
        </DropdownMenuItem>
        
        {user.role_code === 'ADMIN' && (
          <DropdownMenuItem onClick={() => router.push('/admin')}>
            <Settings className="mr-2 h-4 w-4" />
            <span>管理后台</span>
          </DropdownMenuItem>
        )}
        
        <DropdownMenuSeparator />
        
        <DropdownMenuItem 
          onClick={handleLogout}
          disabled={loggingOut}
          className="text-red-600 focus:text-red-600"
        >
          <LogOut className="mr-2 h-4 w-4" />
          <span>{loggingOut ? '登出中...' : '登出'}</span>
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
